package cn.edu.zut.salarymanagesystem.fragments;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;

import cn.edu.zut.salarymanagesystem.R;
import cn.edu.zut.salarymanagesystem.adapter.WorkRecordAdapter;
import cn.edu.zut.salarymanagesystem.bean.pojo.WorkRecord;
import cn.edu.zut.salarymanagesystem.bean.vo.WorksVO;
import cn.edu.zut.salarymanagesystem.config.Storage;
import cn.edu.zut.salarymanagesystem.utils.AlertBuilder;
import cn.edu.zut.salarymanagesystem.utils.Browser;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class QueryFragment extends Fragment implements View.OnClickListener {
    public static final byte GET_LIST = 0x01;
    public static final byte FLUSH_LIST = 0x02;
    private static final byte TOAST_OUT = 0x03;

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_LIST:
                    WorksVO vo = JSON.parseObject((String) msg.obj, WorksVO.class);
                    list = vo.getWorks();
                    adapter.setWorkRecords(list);
                    tvTotal.setText(String.valueOf(vo.getTotal()));
                    adapter.notifyDataSetChanged();
                    break;
                case FLUSH_LIST:
                    if (msg.arg2 == 1) {
                        Toast.makeText(getActivity(), "删除成功！", Toast.LENGTH_SHORT).show();
                        list.remove(msg.arg1);
                        adapter.setWorkRecords(list);
                        adapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(getActivity(), "删除失败！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case TOAST_OUT:
                    Toast.makeText(getActivity(), (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private List<WorkRecord> list = new ArrayList<>();
    private  WorkRecordAdapter adapter;
    private TextView tvTotal;
    private EditText ed_start_date;
    private EditText ed_end_date;
    private String start_date = null;
    private String end_date = null;

    public QueryFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //绑定组件
        View view = inflater.inflate(R.layout.fragment_query, container, false);
        bindView(view);
        initCalendar();
        //请求数据
        OkHttpClient client = Browser.getClient();
        Request request = new Request.Builder().url(Storage.url + "/workRecord/selectAll?pageNum=1&pageSize=1000").build();
        client.newCall(request).enqueue(
                new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Message message = handler.obtainMessage();
                        message.what = GET_LIST;
                        String msg = response.body().string();
                        message.obj = msg;
                        handler.sendMessage(message);
                    }
                }
        );
        return view;
    }

    private void bindView(View view) {
        //界面 & 绑定数据
        view.findViewById(R.id.btn_query).setOnClickListener(queryListener);
        view.findViewById(R.id.btn_start_date).setOnClickListener(startListener);
        view.findViewById(R.id.btn_end_date).setOnClickListener(endListener);
        ((ListView)view.findViewById(R.id.work_list)).setOnItemLongClickListener(itemLongClickListener);
        ((ListView)view.findViewById(R.id.work_list)).setOnItemClickListener(itemClickListener);
        tvTotal = (view.findViewById(R.id.price));
        ed_start_date = view.findViewById(R.id.ed_start_date);
        ed_end_date = view.findViewById(R.id.ed_end_date);
        WorkRecordAdapter adapter = new WorkRecordAdapter(getActivity(), list);
        this.adapter = adapter;
        ((ListView) view.findViewById(R.id.work_list)).setAdapter(adapter);
    }
    // 设置日历
    private void initCalendar(){
        // 设置起始日期为本月第一天
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        start_date = dateFormat.format(calendar.getTime());
        ed_start_date.setText(start_date);

        // 设置结束日期为今天
        end_date = dateFormat.format(System.currentTimeMillis());
        ed_end_date.setText(end_date);
    }

    //查询按钮监听事件
    public View.OnClickListener queryListener = view -> {
        //这里判断是否有选择日期，如果有就查询指定区间的记录，反之就查询全部记录
        OkHttpClient client = Browser.getClient();
        String requstPath;
        if (QueryFragment.this.start_date != null && QueryFragment.this.end_date != null) {
            requstPath = "/workRecord/selectByTime?pageNum=1&pageSize=1000&start=" + start_date + "&end=" + end_date;
        } else {
            Message message = Message.obtain();
            message.what = TOAST_OUT;
            message.obj = "请选择查询日期！";
            handler.sendMessage(message);
            return;
        }
        Request request = new Request.Builder().url(Storage.url + requstPath).build();
        client.newCall(request).enqueue(
                new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Message message = handler.obtainMessage();
                        message.what = GET_LIST;
                        String msg = response.body().string();
                        message.obj = msg;
                        handler.sendMessage(message);
                        Message mess = handler.obtainMessage();
                        mess.obj ="查询成功！";
                        mess.what = TOAST_OUT;
                        handler.sendMessage(mess);
                    }
                }
        );
    };
    //起始日期选择器的监听事件
    private View.OnClickListener startListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Calendar calendar = Calendar.getInstance();
            //此处第一个参数是上下文（对标菜鸟教程中的例子MainActivity.this）
            new DatePickerDialog(getActivity(), (view1, year, month, dayOfMonth) -> {
                ed_start_date.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                start_date = year + "-" + (month + 1) + "-" + dayOfMonth;
            },
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH)).show();
            ed_start_date.setText("");
        }

    };
    //结束日期选择器的监听事件
    private View.OnClickListener endListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Calendar calendar = Calendar.getInstance();
            new DatePickerDialog(getActivity(),
                    (view1, year, month, dayOfMonth) -> {
                        ed_end_date.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                        end_date = year + "-" + (month + 1) + "-" + dayOfMonth;
                    },
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH)).show();
            ed_end_date.setText("");
        }
    };

    //长按删除的监听事件
    public AdapterView.OnItemLongClickListener itemLongClickListener = (adapterView, view, i, l) -> {
        WorkRecord obj = list.get(i);
        //true表示为Append,false表示为Work,如果只用instanceof 只能得到workRecord
        boolean flag = Objects.isNull(obj.getObjectName());
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(obj));
        Request request = new Request.Builder().
                url(Storage.url + "/workRecord/delete" + (flag ? "Append" : "Work")).
                post(body).build();
        AlertBuilder.toSendRequest = request;
        AlertBuilder.getDeleteDialog(QueryFragment.this, "确定要删除吗?", i).show();
        return true;
    };
    @Override
    public void onClick(View v) {

    }

    //短按显示具体记录的监听事件
    public AdapterView.OnItemClickListener itemClickListener=new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            WorkRecord obj=list.get(position);
            AlertBuilder.getDialog(QueryFragment.this,
                    "日期:" +formater.format(obj.getTime())
                    +"\n工件名称:"+obj.getObjectName()
                    +"\n备注:"+obj.getCommentary()
                    +"\n工资:"+obj.getValue()
                    +"\n数量:"+obj.getNumber()
                    +"\n有效性:"+(obj.getValid()==1||obj.getValid()==null?"是":"否")).show();
        }
    };
    private SimpleDateFormat formater = new SimpleDateFormat("yyyy年MM月dd日");
}
